package com.jlnk.androidfmc;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jlnk.androidfmc.adapter.ChatAdapter;
import com.jlnk.androidfmc.entity.Message;
import com.jlnk.androidfmc.fragment.fragments.MessageFragment;


import java.util.Objects;

public class ChatActivity extends AppCompatActivity {

  private ImageView btn_send;
  private EditText et_content;
  private ChatAdapter adapter;
  private RecyclerView recycler_view;

  private ActionBar actionBar;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_chat);
    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
      Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
      v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
      return insets;
    });
    initToolbar();
    iniComponent();
  }

  public void initToolbar() {
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
    Tools.setSystemBarColorInt(this, Color.parseColor("#0C7C41"));
  }

  public void iniComponent() {
    recycler_view = findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recycler_view.setLayoutManager(layoutManager);
    recycler_view.setHasFixedSize(true);

    adapter = new ChatAdapter(this);
    recycler_view.setAdapter(adapter);
    adapter.insertItem(
        new Message(adapter.getItemCount(), "Hi，我是本次接待您的客服，请问有什么可以帮助您？", false,
            adapter.getItemCount() % 5 == 0,
            Tools.getFormattedTimeEvent(System.currentTimeMillis())));
    /*adapter.insertItem(
        new Message(adapter.getItemCount(), "衬衫的价格是多少？", true, adapter.getItemCount() % 5 == 0,
            Tools.getFormattedTimeEvent(System.currentTimeMillis())));*/

    btn_send = findViewById(R.id.btn_send);
    et_content = findViewById(R.id.text_content);
    btn_send.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        sendChat();
      }
    });
    et_content.addTextChangedListener(contentWatcher);
  }

  private void sendChat() {
    final String msg = et_content.getText().toString();
    if (msg.isEmpty()) {
      return;
    }
    adapter.insertItem(
        new Message(adapter.getItemCount(), msg, true, adapter.getItemCount() % 5 == 0,
            Tools.getFormattedTimeEvent(System.currentTimeMillis())));
    et_content.setText("");
    recycler_view.scrollToPosition(adapter.getItemCount() - 1);
    new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
        adapter.insertItem(
            new Message(adapter.getItemCount(), msg, false, adapter.getItemCount() % 5 == 0,
                Tools.getFormattedTimeEvent(System.currentTimeMillis())));
        recycler_view.scrollToPosition(adapter.getItemCount() - 1);
      }
    }, 1000);
  }

  @Override
  public void onPostCreate(@Nullable Bundle savedInstanceState,
      @Nullable PersistableBundle persistentState) {
    super.onPostCreate(savedInstanceState, persistentState);
    hideKeyboard();
  }

  private void hideKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
      InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
  }

  private final TextWatcher contentWatcher = new TextWatcher() {
    @Override
    public void afterTextChanged(Editable etd) {
      if (etd.toString().trim().isEmpty()) {
        btn_send.setImageResource(R.drawable.ic_mic);
      } else {
        btn_send.setImageResource(R.drawable.ic_send);
      }
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    }
  };

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_chat, menu);
    return true;
  }

  // ChatActivity.java 的 onOptionsItemSelected 方法
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
      // 结束当前的ChatActivity，返回到MainActivity
      finish();
      return true;
    }
    return super.onOptionsItemSelected(item);
  }


}